package apipprof

import (
	"net/http/pprof"

	"github.com/gofiber/fiber"
	"github.com/valyala/fasthttp/fasthttpadaptor"
)

var (
	pprofIndex        = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Index)
	pprofCmdline      = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Cmdline)
	pprofProfile      = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Profile)
	pprofSymbol       = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Symbol)
	pprofTrace        = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Trace)
	pprofAllocs       = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Handler("allocs").ServeHTTP)
	pprofBlock        = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Handler("block").ServeHTTP)
	pprofGoroutine    = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Handler("goroutine").ServeHTTP)
	pprofHeap         = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Handler("heap").ServeHTTP)
	pprofMutex        = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Handler("mutex").ServeHTTP)
	pprofThreadcreate = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Handler("threadcreate").ServeHTTP)
)

func AddRoutes(app fiber.Router) {
	app.Get("/debug/pprof/:name?", pprofHandler)
}

func pprofHandler(c *fiber.Ctx) error {
	c.Set("Content-Type", "text/html")
	pName := c.Params("name")
	switch pName {
	case "":
		pprofIndex(c.Context())
	case "cmdline":
		pprofCmdline(c.Context())
	case "profile":
		pprofProfile(c.Context())
	case "symbol":
		pprofSymbol(c.Context())
	case "trace":
		pprofTrace(c.Context())
	case "allocs":
		pprofAllocs(c.Context())
	case "block":
		pprofBlock(c.Context())
	case "goroutine":
		pprofGoroutine(c.Context())
	case "heap":
		pprofHeap(c.Context())
	case "mutex":
		pprofMutex(c.Context())
	case "threadcreate":
		pprofThreadcreate(c.Context())
	}
	return nil
}
